var express = require("express");
var router = express.Router();
const WebSocket = require("ws");
const path = require("path");
const fs = require("fs");

// 创建WebSocket服务器
let wss;
let wsClients = [];

// 初始化WebSocket服务器
function initWebSocket(server) {
  // 使用 noServer 选项，手动处理 upgrade 事件
  wss = new WebSocket.Server({ noServer: true });

  wss.on("connection", (ws) => {
    console.log("新的WebSocket连接");
    wsClients.push(ws);

    // 发送初始数据
    ws.send(
      JSON.stringify({
        type: "init",
        data: getCarData(),
      })
    );

    ws.on("close", () => {
      wsClients = wsClients.filter((client) => client !== ws);
      console.log("WebSocket连接关闭");
    });
  });

  // 心跳机制
  setInterval(() => {
    wsClients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.ping();
      }
    });
  }, 30000);

  // 定时推送数据
  setInterval(() => {
    const data = getCarData();
    wsClients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(
          JSON.stringify({
            type: "update",
            data: data,
          })
        );
      }
    });
  }, 5000);

  // 处理 upgrade 事件，只处理 /jjx 路径的 WebSocket 连接
  server.on('upgrade', (request, socket, head) => {
    const pathname = request.url;
    
    if (pathname === '/jjx/ws') {
      wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
      });
    }
  });
}

// 汽车数据
function getCarData() {
  return {
    summary: {
      totalVehicles: 541,
      bestSellingCar: "Model Y",
      highestSales: 51117,
      bestSellingType: "紧凑型SUV",
      bestSellingBrand: "大众",
      averagePrice: 20.08,
    },
    evVsFuel: [
      { id: 1, name: "思域", sales: 26294, energy: "汽油" },
      { id: 2, name: "速腾", sales: 25566, energy: "汽油" },
      { id: 3, name: "朗逸", sales: 24123, energy: "汽油" },
      { id: 4, name: "轩逸", sales: 23891, energy: "汽油" },
      { id: 5, name: "秦PLUS DM-i", sales: 28154, energy: "混动" },
      { id: 6, name: "Model Y", sales: 51117, energy: "电动" },
      { id: 7, name: "海鸥", sales: 34841, energy: "电动" },
      { id: 8, name: "哈弗H6", sales: 17115, energy: "汽油" },
    ],
    carRanking: [
      {
        rank: 1,
        image: "/src/1.jpg",
        name: "Model Y",
        brand: "特斯拉/特斯拉中国",
        price: "26.39-34.99万元",
        sales: 51117,
        warranty: "4年或8万公里",
        launchDate: "2022.08",
      },
      {
        rank: 2,
        image: "/src/2.jpg",
        name: "海鸥",
        brand: "比亚迪/比亚迪",
        price: "7.38-8.98万元",
        sales: 34841,
        warranty: "6年或15万公里",
        launchDate: "2023.04",
      },
      {
        rank: 3,
        image: "/src/3.jpg",
        name: "朗逸",
        brand: "大众/上汽大众",
        price: "7.49-12.69万元",
        sales: 33891,
        warranty: "3年或10万公里",
        launchDate: "2023.08",
      },
      {
        rank: 4,
        image: "/src/4.jpg",
        name: "轩逸",
        brand: "日产/东风日产",
        price: "8.46-16.29万元",
        sales: 32894,
        warranty: "5年或15万公里",
        launchDate: "2023.03",
      },
      {
        rank: 5,
        image: "/src/5.jpg",
        name: "秦PLUS DM-i",
        brand: "比亚迪/比亚迪",
        price: "9.48-16.08万元",
        sales: 28154,
        warranty: "6年或15万公里",
        launchDate: "2023.02",
      },
    ],
    brandRanking: [
      { rank: 1, name: "大众", categories: 28 },
      { rank: 2, name: "丰田", categories: 26 },
      { rank: 3, name: "本田", categories: 24 },
      { rank: 4, name: "比亚迪", categories: 15 },
      { rank: 5, name: "奥迪", categories: 15 },
      { rank: 6, name: "长安", categories: 14 },
    ],
    salesShare: {
      fuel: 55.86,
      ev: 29.3,
      hybrid: 14.84,
    },
    salesChart: [
      { name: "Model Y", sales: 51117, price: 30.69 },
      { name: "海鸥", sales: 34841, price: 8.18 },
      { name: "朗逸", sales: 24123, price: 12.09 },
      { name: "轩逸", sales: 23891, price: 11.86 },
      { name: "秦PLUS DM-i", sales: 28154, price: 12.78 },
      { name: "思域", sales: 26294, price: 12.99 },
      { name: "元PLUS", sales: 19876, price: 13.98 },
      { name: "宋PLUS DM-i", sales: 18765, price: 15.28 },
      { name: "长安CS75 PLUS", sales: 17654, price: 11.79 },
      { name: "海豚", sales: 16543, price: 11.68 },
      { name: "锋兰达", sales: 15432, price: 12.58 },
    ],
    wordCloud: [
      { name: "汽车", value: 100 },
      { name: "一汽大众", value: 85 },
      { name: "比亚迪", value: 80 },
      { name: "丰田", value: 75 },
      { name: "长城汽车", value: 70 },
      { name: "上汽大众", value: 65 },
      { name: "通用别克", value: 60 },
      { name: "奇瑞", value: 55 },
      { name: "上汽通用", value: 50 },
      { name: "广汽本田", value: 45 },
      { name: "东风日产", value: 40 },
      { name: "广汽丰田", value: 35 },
      { name: "一汽丰田", value: 30 },
    ],
    brandSales: [
      { name: "特斯拉", value: 25 },
      { name: "比亚迪", value: 20 },
      { name: "大众", value: 18 },
      { name: "日产", value: 12 },
      { name: "本田", value: 10 },
      { name: "埃安", value: 8 },
      { name: "长安", value: 7 },
      { name: "丰田", value: 6 },
      { name: "哈弗", value: 3 },
      { name: "五菱汽车", value: 1 },
    ],
    priceDistribution: [
      { range: "0-5万", count: 7 },
      { range: "5-10万", count: 45 },
      { range: "10-15万", count: 156 },
      { range: "15-20万", count: 89 },
      { range: "20万以上", count: 39 },
    ],
  };
}

// 获取汽车数据
router.get("/car-data", function (req, res, next) {
  res.json({
    success: true,
    data: getCarData(),
  });
});

// 导出CSV数据
router.get("/export-csv", function (req, res, next) {
  const data = getCarData();
  let csvContent = "车名,销量,能源类型,价格\n";

  data.evVsFuel.forEach((car) => {
    csvContent += `${car.name},${car.sales},${car.energy},${
      car.price || "N/A"
    }\n`;
  });

  res.setHeader("Content-Type", "text/csv");
  res.setHeader("Content-Disposition", "attachment; filename=car-data.csv");
  res.send(csvContent);
});

// 导出图片数据（返回base64）
router.get("/export-image", function (req, res, next) {
  // 这里可以生成图表的base64数据
  const imageData =
    "";

  res.json({
    success: true,
    data: {
      image: imageData,
      timestamp: new Date().toISOString(),
    },
  });
});

// 初始化WebSocket
router.initWebSocket = initWebSocket;

module.exports = router;
